package com.weilele.mvvm.base

import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.webkit.*
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.weilele.mvvm.databinding.ActivityWebViewHelperBinding
import com.weilele.mvvm.utils.activity.isStatusBarBlackTextColor
import com.weilele.mvvm.utils.activity.navigateTo
import com.weilele.mvvm.utils.activity.setInvisible
import com.weilele.mvvm.utils.byteLengthToString
import com.weilele.mvvm.utils.download.WebViewFileDownload
import com.weilele.mvvm.utils.permission.callPermissions
import com.weilele.mvvm.utils.safeGet
import com.weilele.mvvm.widget.BaseWebView
import java.lang.ref.WeakReference
import java.net.URLDecoder


class WebViewHelperActivity : MvvmActivity() {
    companion object {
        private var it: WeakReference<WebViewHelperActivity>? = null
        private var mUrl: String? = null
        private var mStatusBarColor: Int? = null
        private var mStatusBarTextColorIsBlack: Boolean = false
        private var mStatusBarIsTransparent: Boolean = false
        private var mTitleBar: WeakReference<View>? = null
        private var mShowTitleView: WeakReference<TextView>? = null
        private var cookies: String? = null
        private var isNeedAutoTopButton: Boolean = false
        private var baseWebViewCall: Function1<WeakReference<BaseWebView>, Boolean>? = null
        fun finish() {
            it?.get()?.finish()
        }
    }

    class Builder {
        /**
         * 设置加载的url
         */
        fun setUrl(url: String?): Builder {
            mUrl = url
            return this
        }

        /**
         * 设置状态栏颜色
         */
        fun setStatusBarColor(color: Int?): Builder {
            mStatusBarColor = color
            return this
        }

        /**
         * 设置状态栏文字是否黑色
         */
        fun setStatusBarTextColorIsBlack(isBlack: Boolean): Builder {
            mStatusBarTextColorIsBlack = isBlack
            return this
        }

        /**
         * 设置标题栏
         */
        fun setTitleBar(view: View?): Builder {
            view ?: return this
            mTitleBar = WeakReference(view)
            return this
        }

        /**
         * 设置显示标题的textView
         */
        fun setShowTitleView(view: TextView?): Builder {
            view ?: return this
            mShowTitleView = WeakReference(view)
            return this
        }

        /**
         * 设置cookie
         */
        fun setCookie(cookie: String?): Builder {
            cookie ?: return this
            cookies = cookie
            return this
        }

        /**
         * 设置状态栏是否透明
         */
        fun setStatusBarIsTransparent(isTransparent: Boolean): Builder {
            mStatusBarIsTransparent = isTransparent
            return this
        }

        /**
         * 设置是否需要自动滚动到头顶的按钮
         */
        fun setNeedAutoTopButton(needAutoTopButton: Boolean): Builder {
            isNeedAutoTopButton = needAutoTopButton
            return this
        }

        /**
         * 设置webview回调
         * 由于安全检测，默认很多功能关闭（比如js功能），可以在这里自行开启
         */
        fun setOnWebView(call: Function1<WeakReference<BaseWebView>, Boolean/*是否可以加载之前设置的url*/>?): Builder {
            baseWebViewCall = call
            return this
        }

        /**
         * 启动此activity
         */
        fun start(activity: AppCompatActivity?) {
            activity ?: return
            activity.navigateTo<WebViewHelperActivity>()
        }
    }

    private var isHelperPbShow = false
    private val binding by lazy { ActivityWebViewHelperBinding.inflate(layoutInflater) }
    override fun onMvvmCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Any {
        return binding.root
    }

    override fun getClickView(): List<View?>? = listOf()

    override fun initUi(savedInstanceState: Bundle?) {
        it = WeakReference(this)
        mStatusBarColor?.let {
            window.statusBarColor = it
        }
        isStatusBarBlackTextColor(mStatusBarTextColorIsBlack)
        mTitleBar?.get()?.let {
            binding.helperRootView.addView(
                it, 0, LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
            )
        }
        if (mStatusBarIsTransparent) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
        binding.helperWebView.swipeRefreshLayout = binding.helperLoading
        binding.helperWebView.floatUpTopButton = binding.helperFab
        setLoadListener()
        setDownloadListener()
        binding.helperFab.setInvisible(isNeedAutoTopButton)
    }


    override fun initData() {
        binding.helperLoading.setOnRefreshListener {
            relaod()
        }
        CookieManager.getInstance().setAcceptThirdPartyCookies(binding.helperWebView, true)
        cookies?.let {
            CookieManager.getInstance().setCookie(mUrl, it)
        }
        if (baseWebViewCall?.invoke(WeakReference(binding.helperWebView)) == true) {
            mUrl?.let {
                binding.helperWebView.loadUrl(it)
            }
        }
    }

    override fun onSingleClick(view: View) {
    }

    /**
     * 设置加载监听加载成功，加载失败
     */
    private fun setLoadListener() {
        binding.helperWebView.webViewClient = object : WebViewClient() {
            private var isLoadSuccess: Boolean = true
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                val url = request?.url?.toString() ?: return true
//                try {
//                    if (!URLUtil.isNetworkUrl(url)) {//过滤
//                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
//                        startActivity(intent)//防止开启三方软件
//                        return true
//                    }
//                } catch (e: Exception) {
//                    return true
//                }
                view?.loadUrl(url)
                return true
            }

            override fun onLoadResource(view: WebView?, url: String?) {
                if (url?.endsWith("gif") == false) {
                    super.onLoadResource(view, url)
                } else {
                    view?.stopLoading()
                }
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.helperLoading.isRefreshing = false
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                binding.helperLoading.isRefreshing = false
            }
        }
        binding.helperWebView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress < 100) {
                    if (!isHelperPbShow) {
                        isHelperPbShow = true
                        binding.helperPb.show()
                    }
                    binding.helperPb.progress = newProgress
                } else {
                    if (isHelperPbShow) {
                        isHelperPbShow = false
                        binding.helperPb.hide()
                    }
                }
            }

            override fun onJsBeforeUnload(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean {
                return super.onJsBeforeUnload(view, url, message, result)
            }

            override fun getDefaultVideoPoster(): Bitmap? {
                return super.getDefaultVideoPoster()
            }

            override fun getVideoLoadingProgressView(): View? {
                return super.getVideoLoadingProgressView()
            }

            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                mShowTitleView?.get()?.text = title
                mTitleBar?.get().safeGet<Toolbar>()?.title = title
            }
        }

    }

    /**
     * 设置下载监听
     */
    private fun setDownloadListener() {
        binding.helperWebView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            if (!url.isNullOrBlank()) {
                //需要下载文件
                AlertDialog.Builder(this)
                    .setMessage(
                        "${
                            getFileName(
                                url,
                                contentDisposition,
                                contentDisposition
                            )
                        }\n大小：${contentLength.byteLengthToString()}"
                    )
                    .setCancelable(false)
                    .setTitle("下载提示")
                    .setNegativeButton("取消") { _, _ ->
                    }
                    .setPositiveButton("下载") { _, _ ->
                        callPermissions(listOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            if (it.isEmpty()) {
                                WebViewFileDownload(
                                    this,
                                    url,
                                    getFileName(url, contentDisposition, contentDisposition),
                                    mimetype
                                ).start()
                            }
                        }
                    }
                    .show()
            }
        }
    }

    private fun getFileName(url: String, disposition: String?, type: String?): String {
        return URLDecoder.decode(
            URLUtil.guessFileName(url, disposition, type),
            Charsets.UTF_8.displayName()
        )
        /*     var message = disposition ?: return ""
             val fileName = "filename="

             if (disposition.contains(fileName, true)) {
                 message = disposition.split(fileName)[1].split(";")[0]
             }
             return URLDecoder.decode(message, Charsets.UTF_8.displayName())*/
    }

    override fun onDestroy() {
        it?.clear()
        it = null
        baseWebViewCall = null
        //非常简洁
        CookieManager.getInstance().removeAllCookies(null)
        CookieManager.getInstance().flush()
        super.onDestroy()
        mTitleBar?.clear()
        mTitleBar = null
        mShowTitleView?.clear()
        mShowTitleView = null
        cookies = null
    }

    private fun relaod() {
        binding.helperWebView.reload()
    }

    override fun onBackPressed() {
        if (binding.helperWebView.canGoBack()) {
            binding.helperWebView.goBack()
        } else {
            super.onBackPressed()
        }
    }
}
